package com.yyw.gulimall.product.web;

import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 易煜玮
 * @ClassName ProductTestController.java
 * @Description
 * @createTime 2020年11月29日 12:31:00
 */
@RestController
@RequestMapping("/test")
public class ProductTestController {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 分布式锁测试
     */
    @GetMapping("/save")
    public String save() {
        RLock lock = redissonClient.getLock("save-lock");
        lock.lock();
        // 开始业务方法
        try {
            System.out.println("拿到锁了" + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            lock.unlock();
            System.out.println("释放锁" + Thread.currentThread().getId());
        }
        return "ok";
    }

    /**
     * 信号量测试
     */
    @GetMapping("/partinit")
    public String xinhao() {
        RSemaphore xinhao = redissonClient.getSemaphore("xinhao");
        xinhao.trySetPermits(5);
        return "ok";
    }

    @GetMapping("/part")
    public String part() {
        RSemaphore xinhao = redissonClient.getSemaphore("xinhao");
        try {
            xinhao.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping("/go")
    public String go() {
        RSemaphore xinhao = redissonClient.getSemaphore("xinhao");
        xinhao.release();
        return "ok";
    }
}
